--[[
Licenced under GNU GPL.
For more information, see LICENCE in the main folder.
--]]
require "./AI/USER_AI/easyai/ai/Global.lua"
require "./AI/USER_AI/easyai/util/Computations.lua"
require "./AI/USER_AI/easyai/util/List.lua"

--[[
State Class.

@version	0.1 23 Aug 2011
@author		rodmp
--]]
State = {
    currentState = 0,		-- Current State of AI.
    idleState = 0,		-- Idle State.
    followState = 1,		-- Follow State.
    chaseState = 2,		-- Chase State.
    attackState = 3		-- Attack State.
}

function State:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self

    return o
end

function State:setCurrentState(state)
    self.currentState = state
end

function State:getCurrentState()
    return self.currentState
end

function State:doIdle()
    local cmd = List.popleft(ResCmdList)
    local distance = 0
    local target = 0
    local comp = Computations:new()

    if (cmd ~= nil) then		
        ProcessCommand (cmd)
        return 
    end

    -- Search for new targets.
    --target = homun:getNewTarget()

    if (target ~= 0) then
        myEnemy:setID(target)

        -- Check distance to decide whether to attack or chase it.
        if (comp:isTargetTooFar(homun:getID(), myEnemy:getID())) then
            myState:setCurrentState(2)
        else
            myState:setCurrentState(3)
        end

        return
    end

    -- If distance from owner is greater than threshold then go to follow state.
    distance = comp:getDistanceFrom(homun:getID(), owner:getID())

    if (distance > 1) then
        myState:setCurrentState(1)
        return
    end

    TraceAI("Check if idle is working.")
end

function State:doFollow()
    local comp = Computations:new()

    if (comp:getDistanceFrom(homun:getID(), owner:getID()) <= 3) then
        myState:setCurrentState(0)
        return
    else--if (GetV(V_MOTION, homun:getID()) == MOTION_STAND) then
        MoveToOwner(homun:getID())
        return
    end
end

function State:doChase()
    local x, y = 0, 0
    local comp = Computations:new()

    if (comp:isTargetTooFar(homun:getID(), myEnemy:getID())) then
        myEnemy:setID(0)
        myState:setCurrentState(0)
        return
    end

    if (comp:isCloseToAttack(homun:getID(), myEnemy:getID())) then
        myState:setCurrentState(3)
        return
    end

    x, y = GetV(V_POSITION, myEnemy:getID())

    Move(homun:getID(), x, y)
    return
end

function State:doAttack()
    local comp = Computations:new()

    if ((comp:isTargetTooFar(homun:getID(), myEnemy:getID())) or (GetV(V_MOTION, myEnemy:getID() == MOTION_DEAD))) then
        myEnemy:setID(0)
        myState:setCurrentState(0)
        return
    end

    if (comp:isTargetTooFar(homun:getID(), myEnemy:getID())) then
        myState:setCurrentState(2)
        return
    end

    Attack(homun:getID(), myEnemy:getID())
    return
end